package com.ruoyi.apiserver.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.ruoyi.apiserver.utils.JwtUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.StringUtils;

/**
 * JWT拦截器
 * 
 * @author ruoyi
 */
@Component
public class JwtInterceptor implements HandlerInterceptor
{
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        System.out.println("JWT拦截器处理请求: " + request.getRequestURI());
        
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 调试：打印所有注解
        System.out.println("方法注解数量: " + handlerMethod.getMethod().getAnnotations().length);
        for (java.lang.annotation.Annotation annotation : handlerMethod.getMethod().getAnnotations()) {
            System.out.println("方法注解: " + annotation.annotationType().getName());
            // 检查是否是@Anonymous注解
            if (annotation.annotationType().getName().equals("com.ruoyi.common.annotation.Anonymous")) {
                System.out.println("找到@Anonymous注解！跳过token验证");
                return true;
            }
        }
        
        // 检查类级别注解
        System.out.println("类注解数量: " + handlerMethod.getBeanType().getAnnotations().length);
        for (java.lang.annotation.Annotation annotation : handlerMethod.getBeanType().getAnnotations()) {
            System.out.println("类注解: " + annotation.annotationType().getName());
            // 检查是否是@Anonymous注解
            if (annotation.annotationType().getName().equals("com.ruoyi.common.annotation.Anonymous")) {
                System.out.println("类级别找到@Anonymous注解！跳过token验证");
                return true;
            }
        }
        
        // 检查是否有@Anonymous注解（方法级别）
        if (handlerMethod.hasMethodAnnotation(Anonymous.class))
        {
            System.out.println("方法有@Anonymous注解，跳过token验证: " + handlerMethod.getMethod().getName());
            return true;
        }
        
        // 检查类级别是否有@Anonymous注解
        if (handlerMethod.getBeanType().getAnnotation(Anonymous.class) != null)
        {
            System.out.println("类有@Anonymous注解，跳过token验证: " + handlerMethod.getBeanType().getSimpleName());
            return true;
        }

        // 获取请求头中的token
        String token = jwtUtils.getToken(request);
        if (StringUtils.isEmpty(token))
        {
            System.out.println("Token为空，返回401错误");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setStatus(403);
            response.getWriter().write("{\"code\":403,\"msg\":\"令牌不能为空\"}");
            return false;
        }

        // 验证token是否有效
        if (!jwtUtils.validateToken(token))
        {
            System.out.println("Token验证失败，返回403错误");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setStatus(403);
            response.getWriter().write("{\"code\":403,\"msg\":\"令牌已过期或无效\"}");
            return false;
        }

        return true;
    }
}